/**
*   \file   spheresphere.h
*   \author Dave Reid
*   \brief  Header file for checking if two spheres intersect or are just touching.
*/
#ifndef __EAGL_INTERSECT_SPHERESPHERE_H_
#define __EAGL_INTERSECT_SPHERESPHERE_H_

#include "../types.h"

namespace eagl
{

struct INTERSECT_RESULT
{
    /// The position on the first object that the intersection took place.
    vec3 intersectPos0;

    /// The position on the second object that the intersection took place.
    vec3 intersectPos1;

    /// The depth of the collision.
    float depth;
};


inline bool intersect_spheresphere(const vec3 &sphere0Pos, float sphere0Radius,
                                   const vec3 &sphere1Pos, float sphere1Radius,
                                   INTERSECT_RESULT *result = 0)
{
    vec3 d(sphere0Pos - sphere1Pos);

    if (result == 0)
    {
        return glm::dot(d, d) <= ((sphere0Radius + sphere1Radius) * (sphere0Radius + sphere1Radius));
    }
    else
    {
        // If the distance between the positions is larger than the sum of the two radii, there was no
	    // collision.
        float dist = glm::length(d);
	    if (dist > sphere0Radius + sphere1Radius)
	    {
            return false;
	    }
        else
        {
	        // Grab the normal of the difference.
	        vec3 diff_norm(glm::normalize(d));

	        // Now determine the positions on the spheres (in world coordinates) that the collision took place.
            result->intersectPos0 = sphere0Pos + (diff_norm * sphere0Radius);
	        result->intersectPos1 = sphere1Pos - (diff_norm * sphere1Radius);

	        // Find the penetration depth, which is simply the distance between the two collision points.
            result->depth = glm::abs(dist - (sphere0Radius + sphere1Radius));

            return true;
        }
    }
}


}

#endif  // __EAGL_INTERSECT_SPHERESPHERE_H_